<?php


namespace iflow\template\document\Tag;


use iflow\template\config\Config;
use iflow\template\document\abstracts\TagAbstract;
use iflow\template\document\Parser\DOMNodeParser;
use iflow\template\document\Parser\ParserHtml;

class Db extends TagAbstract {

    public string $tagName = 'db';

    // 查询语句
    protected string|null $sql = '';

    // 查询方法
    protected string|null $queryAction = '';

    // 查询模型
    protected string $queryModel = '';

    protected string|null $parameterName = '';

    protected string $DB = "\\iflow\\facade\\Db";

    protected array $hiddenAttributes = [
        'action', 'model', 'sql', 'parametername', 'props', 'tag'
    ];

    public function __construct() {
        $this->DB = class_exists($this -> DB) ? $this->DB : "\\think\\facade\\Db";
    }

    public function parser(DOMNodeParser $node, Config $config, ParserHtml $parserHtml): static
    {
        parent::parser($node, $config, $parserHtml); // TODO: Change the autogenerated stub
        $this->queryAction = $this->node -> getAttributes('action') ?: 'query';
        $this->queryModel =  $this->node -> getAttributes('model') ?: '\think\facade\Db';
        $this->sql = $this->node -> getAttributes('sql');
        $this->parameterName = $this->node -> getAttributes('parameterName');
        return $this->parserAttributes();
    }

    public function parserAttributes(): static {
        // TODO: Implement parserAttributes() method.
        $this->html .= "<?php ";
        $this->html .= $this->parameterName ? "{$this -> parameterName} = " : "";
        $props = $this -> props ? "...[{$this -> props}]" : "";

        if ($this->sql) {
            $this->html .= "$this->DB::{$this -> queryAction}(\"{$this->sql}\", $props)";
        } else if ($this->queryModel) {
            $this->html .= "app('{$this -> queryModel}') -> {$this -> queryAction}($props)";
        }
        $this->html .= ";?>";
        $this->html .= $this->traverseNodesToHtml();
        return $this;
    }
}